/*
 *  Copyright (C) 2010 jp
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.boc.botv.web.controller;

import com.boc.botv.common.Database;
import com.boc.botv.model.Bet;
import com.boc.botv.model.BetInstance;
import com.boc.botv.model.PaymentMethod;
import com.boc.botv.model.User;
import com.boc.botv.service.BetManager;
import com.boc.botv.service.PaymentMethodManager;
import com.boc.botv.service.UserManager;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author jp
 */
@Controller
@RequestMapping("/profil/")
public class ProfileController {

  private Map<String, Object> map = new HashMap<String, Object>();
  @Autowired
  private BetManager betManager;
  @Autowired
  private UserManager manager;
  @Autowired
  private PaymentMethodManager paymentMethodManager;

  public ProfileController() {
    map.put("menu", "home");
    map.put("path", "../");
  }

  @RequestMapping(value = "{login}/index", method = RequestMethod.GET)
  public String indexHandler(@PathVariable("login") String login, Model model) {
    Database.startTransaction(true);
    User u = manager.getUser(login);
    if (u == null) {
      Database.closeTransaction();
      return "redirect:/index.htm";
    }
    model.addAllAttributes(map);
    model.addAttribute("title", String.format("%1$s %2$s", u.getFirstName(), u.getLastName()));
    model.addAttribute(u);
    Database.closeTransaction();
    return "/profile/index";
  }

  @RequestMapping(value = "{login}/informations-personnelles", method = RequestMethod.GET)
  public String personnalDataHandler(@PathVariable("login") String login, Model model) {
    Database.startTransaction(true);
    User u = manager.getUser(login);
    if (u == null) {
      Database.closeTransaction();
      return "redirect:/index.htm";
    }
    model.addAllAttributes(map);
    model.addAttribute("title", String.format("Informations personnelles de %1$s %2$s", u.getFirstName(), u.getLastName()));
    model.addAttribute(u);
    Database.closeTransaction();
    return "/profile/infos";
  }

  @RequestMapping(value = "{login}/paris", method = RequestMethod.GET)
  public String betsDataHandler(@PathVariable("login") String login, Model model) {
    Database.startTransaction(true);
    User u = manager.getUser(login);
    if (u == null) {
      Database.closeTransaction();
      return "redirect:/index.htm";
    }
    Set<BetInstance> bi = u.getBetInstances();
    List<Bet> b = betManager.getBets();
    //List<BetChoice> bc = betChoiceManager.getBetChoices();

    model.addAllAttributes(map);
    model.addAttribute("title", String.format("Paris de %1$s %2$s", u.getFirstName(), u.getLastName()));
    model.addAttribute(u);
    if (bi != null) {
      model.addAttribute(bi);
    }
    Database.closeTransaction();
    return "/profile/paris";
  }

  @RequestMapping(value = "{login}/comptes", method = RequestMethod.GET)
  public String accountDataHandler(@PathVariable("login") String login, Model model) {
    Database.startTransaction(true);
    User u = manager.getUser(login);
    if (u == null) {
      Database.closeTransaction();
      return "redirect:/index.htm";
    }
    PaymentMethod pm = u.getPaymentMethod();
    model.addAllAttributes(map);
    model.addAttribute("title", String.format("Comptes bancaires de %1$s %2$s", u.getFirstName(), u.getLastName()));
    model.addAttribute("user", u);
    boolean isEmpty = true;
    if (pm != null) {
      model.addAttribute("paymentMethod", pm);
      isEmpty = pm.getCardName().equals("");
    }
    model.addAttribute("isEmpty", isEmpty);
    Database.closeTransaction();
    return "/profile/account";
  }

  @RequestMapping(value = "update-ident-profile", method = RequestMethod.POST)
  public String updateIdentProfile(
          @RequestParam(value = "login", required = true) String login,
          @RequestParam(value = "email", required = true) String email,
          @RequestParam(value = "password", required = true) String password,
          @RequestParam(value = "npasword", required = false) String npassword,
          @RequestParam(value = "cnpassword", required = false) String cnpassword,
          Model model) {
    Database.startTransaction(false);
    User user = manager.getUser(login);
    boolean r = false;
    if (user != null && manager.checkPassword(login, password)) {
      user.setEmail(email);
      if (npassword != null && cnpassword != null && !npassword.equals(cnpassword) && !npassword.equals("")) {
        user.setPassword(manager.encryptPassword(password));
      }
      r = manager.updateUser(user);
    }
    model.addAttribute("result", r ? "1" : "0");
    model.addAllAttributes(map);
    Database.closeTransaction();
    return "/profile/xml/check";
  }

  @RequestMapping(value = "update-ident-data", method = RequestMethod.POST)
  public String updateIdentData(
          @RequestParam(value = "login", required = true) String login,
          @RequestParam(value = "firstname", required = true) String firstname,
          @RequestParam(value = "lastname", required = true) String lastname,
          @RequestParam(value = "address0", required = true) String address0,
          @RequestParam(value = "address1", required = false) String address1,
          @RequestParam(value = "address2", required = false) String address2,
          @RequestParam(value = "zipcode", required = true) String zipcode,
          @RequestParam(value = "city", required = true) String city,
          @RequestParam(value = "country", required = true) String country,
          @RequestParam(value = "birthdatewrapper", required = true) Date birthDateWrapper,
          @RequestParam(value = "phonehome", required = false) String phonehome,
          @RequestParam(value = "phonegsm", required = false) String phonegsm,
          Model model) {
    Database.startTransaction(false);
    User user = manager.getUser(login);
    boolean r = false;
    if (user != null
            && !firstname.equals("")
            && !lastname.equals("")
            && !address0.equals("")
            && !zipcode.equals("")
            && !city.equals("")
            && !country.equals("")) {
      user.setAddress0(address0);
      user.setAddress1(address1);
      user.setAddress2(address2);
      user.setFirstName(firstname);
      user.setLastName(lastname);
      user.setZipCode(zipcode);
      user.setCity(city);
      user.setCountry(country);
      user.setBirthDate(birthDateWrapper);
      user.setPhoneHome(phonehome);
      user.setPhoneGsm(phonegsm);

      r = manager.updateUser(user);
    }
    model.addAttribute("result", r ? "1" : "0");
    model.addAllAttributes(map);
    Database.closeTransaction();
    return "/profile/xml/check";
  }

  @RequestMapping(value = "update-ident-mailing", method = RequestMethod.POST)
  public String updateIdentMailing(
          @RequestParam(value = "login", required = true) String login,
          @RequestParam(value = "acceptNewsletterSite", required = false) Boolean acceptNewsletterSite,
          @RequestParam(value = "acceptNewsletterPartners", required = false) Boolean acceptNewsletterPartners,
          Model model) {
    Database.startTransaction(false);
    User user = manager.getUser(login);
    boolean r = false;
    if (user != null) {
      user.setAcceptNewsletterPartners(acceptNewsletterPartners);
      user.setAcceptNewsletterSite(acceptNewsletterSite);
      r = manager.updateUser(user);
    }
    model.addAttribute("result", r ? "1" : "0");
    model.addAllAttributes(map);
    Database.closeTransaction();
    return "/profile/xml/check";
  }

  @RequestMapping(value = "delete-card.htm", method = RequestMethod.POST)
  public String deleteCard(
          @RequestParam(value = "uid", required = true) int userId,
          Model model) {
    Database.startTransaction(false);
    boolean r = manager.deletePaymentMethod(userId);
    model.addAttribute("result", r ? "1" : "0");
    Database.closeTransaction();
    return "/xml/boolean";
  }

  @RequestMapping(value = "create-card.htm", method = RequestMethod.POST)
  public String createCard(
          @RequestParam(value = "uid", required = true) int userId,
          @RequestParam(value = "name", required = true) String ownerName,
          @RequestParam(value = "cardName", required = true) String cardName,
          @RequestParam(value = "cardNumber", required = true) String cardNumber,
          @RequestParam(value = "cardExpirationDate", required = true) String ced,
          @RequestParam(value = "cardCryptogram", required = true) String cardCryptogram,
          Model model) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyy/MM/dd");
    Date cardExpirationDate = new Date();
    try {
      cardExpirationDate = sdf.parse(ced);
    } catch (ParseException ex) {
    }

    Database.startTransaction(false);
    boolean r = manager.addPaymentMethod(userId, ownerName, cardNumber, cardName, cardExpirationDate, cardCryptogram);
    model.addAttribute("result", r ? "1" : "0");
    Database.closeTransaction();
    return "/xml/boolean";
  }
}
